package fr.capsuleaube.android.utils;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PageDownloader {

    public String download(String... params) throws IOException {
        String pageContent = "";

        List<NameValuePair> httpParamsList = new ArrayList<NameValuePair>();
        for (int i = 2; i < params.length; i++) {
            // Split arguments
            if (params[i].contains("=")) {
                String[] paramPairs = params[i].split("=");
                if (paramPairs.length == 2) {
                    String argKey = params[i].split("=")[0];
                    String argValue = params[i].split("=")[1];
                    httpParamsList.add(new BasicNameValuePair(argKey, argValue));
                }
            }
        }

        if (params[1].equals("GET")) {
            pageContent = executeHttpRequest("GET", params[0], httpParamsList);
        } else if (params[1].equals("POST")) {
            pageContent = executeHttpRequest("POST", params[0], httpParamsList);
        }

        return pageContent;
    }

    private String executeHttpRequest(String method, String URL, List<NameValuePair> httpParamsList) throws IOException {

        HttpClient httpclient = new DefaultHttpClient();
        ResponseHandler<String> httpResponseHandler = new BasicResponseHandler();

        if (method.equals("POST")) {
            HttpPost httpRequest = new HttpPost(URL);
            httpRequest.setEntity(new UrlEncodedFormEntity(httpParamsList));
            return httpclient.execute(httpRequest, httpResponseHandler);
        } else if (method.equals("GET")) {
            String formattedParamsString = URLEncodedUtils.format(httpParamsList, "utf-8");
            HttpGet httpRequest = new HttpGet(URL + "?" + formattedParamsString);
            return httpclient.execute(httpRequest, httpResponseHandler);
        } else {
            return null;
        }
    }
}